#!/bin/sh

symlink_action() {
	case "$ACTION" in
		add) ln -sf "$1" "$2";;
		remove) rm -f "$2";;
	esac
}

# cdrom symlink
case "$MDEV" in
	sr*|xvd*)
		caps="$(cat /sys/block/$MDEV/capability 2>/dev/null)"
		if [ $(( 0x${caps:-0} & 8 )) -gt 0 ]; then
			symlink_action $MDEV cdrom
		fi
esac

# by-id symlinks
mkdir -p disk/by-id

partition=$(cat /sys/class/block/$MDEV/partition 2>/dev/null)
case "$partition" in
	[0-9]*) partsuffix="-part$partition";;
esac

wwid=$(cat /sys/class/block/$MDEV/wwid 2>/dev/null)
: ${wwid:=$(cat /sys/class/block/$MDEV/device/wwid 2>/dev/null)}

if [ -n "$wwid" ]; then
	case "$MDEV" in
		nvme*) symlink_action ../../$MDEV disk/by-id/nvme-${wwid}${partsuffix};;
	esac
	case "$wwid" in
		naa.*) symlink_action ../../$MDEV disk/by-id/wwn-0x${wwid#naa.};;
	esac
fi

serial=$(sed -E -e 's/^\s+//' -e 's/\s+$//' -e 's/ /_/g' \
	/sys/class/block/$MDEV/device/serial 2>/dev/null)

model=$(sed -E -e 's/^\s+//' -e 's/\s+$//' -e 's/ /_/g' \
	/sys/class/block/$MDEV/device/model 2>/dev/null)

if [ -n "$serial" ] && [ -n "$model" ]; then
	case "$MDEV" in
		nvme*) symlink_action ../../$MDEV disk/by-id/nvme-${model}_${serial}${partsuffix};;
	esac
fi

# virtio-blk
if [ -n "$serial" ]; then
	case "$MDEV" in
		vd*) symlink_action ../../$MDEV disk/by-id/virtio-${serial}${partsuffix};;
	esac
fi

# by-uuid, by-partuuid
eval $(blkid /dev/$MDEV | cut -d: -f2-)
if [ -n "$UUID" ]; then
	mkdir -p disk/by-uuid
	symlink_action ../../$MDEV disk/by-uuid/$UUID
fi
if [ -n "$PARTUUID" ]; then
	mkdir -p disk/by-partuuid
	symlink_action ../../$MDEV disk/by-partuuid/$PARTUUID
fi

